import { resolve, join, extname } from 'path'
import fs from 'fs'

// 加载插件模块
const loadPluginModules = async () => {
  return new Promise(async success => {
    const modulesPath = resolve(__dirname, 'plugins')
    const fileNames = fs.readdirSync(modulesPath)
    const modulesImprot = []
    fileNames.forEach(async item => {
      const filePath = join(modulesPath, item)
      if (
        fs.statSync(filePath).isFile() && [ '.js' ].includes(extname(filePath))
      ) {
        modulesImprot.push(import(`./plugins/${item}`))
      }
    })

    const modules = await Promise.all(modulesImprot)
    success(modules)
  })
}

// 基本配置
const baseCfg = (viteEnv = {}) => {
  const { VITE_BASE_URL } = viteEnv
  return {
    base: './',
    envDir: 'venv',
    resolve: {
      alias: {
        '@': resolve('./src'),
        '~@': resolve('./src')
      },
      extensions: [ '.js', '.mjs', '.vue', '.json', '.scss', '.css' ]
    },
    server: {
      host: '0.0.0.0',
      port: 8888,
      open: false,
      cors: true
    },
    proxy: {
      [`^${VITE_BASE_URL}/.*`]: {
        target: VITE_BASE_URL,
        changeOrigin: true,
        rewrite: path => {
          const reg = new RegExp(`^${VITE_BASE_URL}/`, 'g')
          return path.replace(reg, '')
        }
      }
    },
    build: {
      outDir: 'dist',
      minify: 'terser',
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: '[ext]/[name]-[hash].[ext]'
        }
      }
    },
    css: {
      /* CSS 预处理器 */
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/styles/variable.scss";'
        }
      },
      postcss: {
      }
    }
  }
}

// 插件配置
const pluginCfg = async (viteEnv = {}) => {
  const modulesArr = []
  const modules = await loadPluginModules()
  modules.forEach(item => {
    const funcs = Object.values(item)
    funcs.forEach(it => {
      modulesArr.push(it(viteEnv))
    })
  })
  return modulesArr
}

export { baseCfg, pluginCfg }
